package vn.vfriends.soffice.filter;

import java.io.IOException;
import java.util.List;
import javax.faces.application.ResourceHandler;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.soffice.entity.Group;
import vn.vfriends.soffice.entity.User;
import vn.vfriends.soffice.service.GroupService;

/**
 *
 * @author chaungoctuan@gmail.com
 */
@WebFilter(filterName="SecurityFilter", urlPatterns="/*")
public class SecurityFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(SecurityFilter.class);
    @Inject private GroupService groupService;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hreq = (HttpServletRequest) request;
        
        String servletPath = hreq.getServletPath();
        String pathInfo = hreq.getPathInfo();
        
        String link = servletPath
                + (pathInfo != null ? pathInfo : "");
        
        //  Ignore resource links and webservice links
        if (!link.startsWith(ResourceHandler.RESOURCE_IDENTIFIER) && link.indexOf("resources") < 0) {
            List<Group> ownerGroups = this.groupService.findByURL(link);
            if (ownerGroups.isEmpty()) {
                logger.debug("URL " + link + " is not secured.");
            } else {
                HttpSession session = hreq.getSession(true);
                User loggedUser = (User) session.getAttribute("LOGGED_USER");
                if (loggedUser == null) {
                    HttpServletResponse resp = (HttpServletResponse) response;
                    resp.sendRedirect(hreq.getContextPath() + "/login.jsf");
                    return;
                } else {
                    List<String> availableUrls = (List<String>) session.getAttribute("AVAILABLE_URLS");
                    
                    if(!availableUrls.contains(link)) {
                        HttpServletResponse resp = (HttpServletResponse) response;
                        resp.sendRedirect(hreq.getContextPath() + "/403.jsf");
                        return;
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {}
}
